package com.cop4331.social;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * 
 * @author Matt Szoke
 * @LastUpdated: 4/12/2012 by Matt Szoke
 * 
 * Allows user to register account for app
 * 
 */
public class RegisterActivity extends Activity {

	EditText userName;
	EditText full;
	EditText email;
	EditText phone;
	EditText pw;
	EditText rpw;
	EditText answer;
	EditText major;
	TextView err;
	Button register;
	Button cancel;
	Spinner spinner;
	Spinner spinner_question;

	// -----------------------------------------------
	// ONCREATE
	// -----------------------------------------------
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);

		// User input text fields
		userName = (EditText) findViewById(R.id.tf_un);
		full = (EditText) findViewById(R.id.tf_fullname);
		email = (EditText) findViewById(R.id.tf_email);
		phone = (EditText) findViewById(R.id.tf_phone);
		rpw = (EditText) findViewById(R.id.tf_repass);
		pw = (EditText) findViewById(R.id.tf_password);
		answer = (EditText) findViewById(R.id.tf_answer);
		major = (EditText) findViewById(R.id.tf_major);

		phone.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

		// Error display for user
		err = (TextView) findViewById(R.id.tv_error);

		// Buttons
		register = (Button) findViewById(R.id.b_register);
		cancel = (Button) findViewById(R.id.cancel);

		// Spinners
		spinner = (Spinner) findViewById(R.id.s_gender); // Holds male/female
		spinner_question = (Spinner) findViewById(R.id.s_security); // Holds
																	// available
																	// questions

		// Add functionality to "Register" button
		register.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				// Registration Values
				String un = userName.getText().toString();
				String fullName = full.getText().toString();
				String em = email.getText().toString();
				String phoneNum = phone.getText().toString();
				String pass = pw.getText().toString();
				String rpass = rpw.getText().toString();
				String gender = spinner.getSelectedItem().toString();
				String question = spinner_question.getSelectedItem().toString();
				String ans = answer.getText().toString();
				String maj = major.getText().toString();

				// No Username
				if (un.compareTo("") == 0) {
					err.setText("Please enter a username.");
				}

				else if (!UserFunctions.stringValid(un)) {
					err.setText("Please enter a valid username.");
				}

				else if (Character.isDigit(un.charAt(0))) {
					err.setText("Please enter a valid username.");
				}

				// Contains spaces
				else if (un.contains(" ")) {
					err.setText("Your username cannot contain any spaces.");
				}

				// Un too short
				else if (un.length() < 6) {
					err.setText("The username must be at least 6 characters long.");
				}

				// No Name
				else if (fullName.compareTo("") == 0) {
					err.setText("Please enter your full name.");
				}

				// No Email
				else if (em.compareTo("") == 0) {
					err.setText("Please enter an email address.");
				}

				else if (!UserFunctions.validEmail(em)) {
					err.setText("Please enter a valid email.");
				}

				// Wrong format
				else if (!em.contains(".") || !em.contains("@")
						|| em.contains(" ")) {
					err.setText("Please enter the email address as follows: example@gmail.com");
				}

				// No Password
				else if (pass.compareTo("") == 0) {
					err.setText("Please enter a password.");
				} else if (ans.compareTo("") == 0) {
					err.setText("Please answer your security question.");
				}

				else if (!UserFunctions.stringValid(pass)) {
					err.setText("Please enter a valid password.");
				}

				// Same UN/PW
				else if (pass.compareTo(un) == 0) {
					err.setText("The password cannot be the same as the username");
				}

				// Pass to short
				else if (pass.length() < 6) {
					err.setText("The password must be at least 6 characters long.");
				}

				// Contains spaces
				else if (pass.contains(" ")) {
					err.setText("Your password cannot contain any spaces.");
				}

				// Password does not match
				else if (pass.compareTo(rpass) != 0) {
					err.setText("Password does not match.");
				}

				else if (maj.length() == 0) {
					maj = "N/A";
				}

				else {

					UserFunctions userFunction = new UserFunctions();

					// Add to database, image is defaulted to - default.jpg
					JSONObject json = userFunction.registerUser(un, fullName,
							em, phoneNum, pass, "default.jpg", gender,
							question, ans, maj);

					try {
						if (json.getString("success") != null) {

							err.setText("");
							String res = json.getString("success");

							// Returned 0 because a username like this already
							// exists.
							if (Integer.parseInt(res) == 0) {
								err.setText("User already exists.");
							}

							// Added user successfully
							else {

								// Bundle username for ImageuploadActivity slide
								Bundle b = new Bundle();
								b.putString("username", un);
								
								// Send new user a welcome message
								userFunction.addMessage(
												"CramSessions",
												un,
												"Welcome to CramSessions!",
												"Thanks for joining CramSessions.  To begin using our services, at the dashboard menu select view profile.  "
														+ "From there, you can add classes and opt to tutor in classes in which you meet the requirements.  To find a tutor, select a find a tutor option!");

								// Call imageuploadactivity, add extras
								Intent ImageUpload = new Intent(
										getApplicationContext(),
										ImageuploadActivity.class);
								ImageUpload.putExtras(b);

								startActivity(ImageUpload);
								finish();
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		});

		// Cancel button, return to loginactivity
		cancel.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent log = new Intent(getApplicationContext(),
						LoginActivity.class);
				startActivity(log);
				finish();

			}
		});
	}
}
